#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QDebug>
#include"sqliteoperator.h"
#include"comment.h"
#include<string.h>
#include<stdio.h>
#include <QJsonParseError>
#include <QJsonObject>
#include <unistd.h>
#include <iostream>
#include <chrono>
#include <thread>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //创建服务器对象
    server = new QTcpServer(this);
    //设置端口号
    server->listen(QHostAddress::Any,9000);
    //连接信号,把客户端连接的消息和槽函数关联
    connect(server,&QTcpServer::newConnection,this,&MainWindow::acceptConnect);

    //    QPainter painter(this);
    //    painter.drawPixmap(0,0,width(),height(),QPixmap(":/微信图片_20240827155323.png"));
    //创建数据库连接
    sqliteOP = new SqliteOperator;
    sqliteOP->openDb();//打开数据库
    //执行数据库操作（创建表格）
//    sqliteOP->normalExec("create table user(name varchar(128),passwd varchar(128))");
    //    sqliteOP->closeDb();
}

MainWindow::~MainWindow()
{
    sqliteOP->closeDb();
    delete ui;
}
void MainWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(0,0,width(),height(),QPixmap(":/微信图片_20240827155323.png"));

}

void MainWindow::acceptConnect()
{
    clientSocket = server->nextPendingConnection();//检查是否有新的客户端连接请求


    //如果客户端发来消息会收到一个readyRead的信号
    connect(clientSocket,&QTcpSocket::readyRead,this,&MainWindow::onReadyRead);
    //如果客户端断开连接，也会收到断开连接的信号，这里关联一个专门处理客户端断开连接的槽函数
    connect(clientSocket,&QTcpSocket::disconnected,this,&MainWindow::onDisconnected);


}

void MainWindow::onReadyRead()
{
    if(clientSocket)
    {
        QMSG msg;
        int ret = clientSocket->read((char*)&msg,sizeof(msg));//读取发过来的数据,并将读取的消息存入msg
        qDebug()<<ret<<" "<<msg.type<<endl;
        if(msg.type == 1)//注册
        {
            user * rn = (user*)msg.buf;
            ui->textEdit->append(rn->name);
            ui->textEdit->append(rn->passwd);
            QString str= QString("insert into user values('%1','%2')").arg(rn->name).arg(rn->passwd);
            sqliteOP->normalExec(str);
            qDebug()<<rn->name<<endl;
            QString str1= QString("create table like%1(songname varchar(128),singer varchar(128),album varchar(128),duration int,id int,state varchar(128))").arg(rn->name);
            sqliteOP->normalExec(str1);
            qDebug()<<rn->passwd<<endl;

            char buf[128] = "get1";
            strcpy(msg.buf,buf);
            clientSocket->write((char*)&msg,sizeof(msg));
        }
        if(msg.type == 2)//登录
        {
            user * rn = (user*)msg.buf;
            name=rn->name;
            QSqlQuery sqlQuery;
            QString str= QString("select * from user where name='%1' and passwd='%2'").arg(rn->name).arg(rn->passwd);
            sqliteOP->normalQuery(sqlQuery,str);
            if(sqlQuery.next())
            {
                char buf[128] = "get2";
                strcpy(msg.buf,buf);
                clientSocket->write((char*)&msg,sizeof(msg));
                qDebug()<<"用户登录成功"<<endl;
            }
        }
        if(msg.type == 3)//喜欢
        {
//            qDebug()<<"msg.buf"<<msg.buf<<endl;
            song*rn=new song;
            rn = (song *)msg.buf;
//            qDebug()<<rn->singer<<rn->songname<<endl;
            QString str= QString("insert into like%1 values('%2','%3','%4',%5,%6,1)").arg(name).arg(rn->songname).arg(rn->singer).arg(rn->album_name).arg(rn->duration2).arg(rn->music_id);
            sqliteOP->normalExec(str);
        }
        if(msg.type == 4)//遍历喜欢列表
        {
            QSqlQuery sqlQuery;
            qDebug()<<"接收了"<<i<<"次信号"<<endl;
            QString str= QString("select * from like%1").arg(name);
            sqliteOP->normalQuery(sqlQuery, str);
            song s;
            while(1)
            {
                if(!sqlQuery.next())
                {
                    msg.type=404;
                    clientSocket->write((char*)&msg,sizeof(msg));
                    return;
                }
                QString songname = sqlQuery.value(0).toString();
                QString singer =sqlQuery.value(1).toString();
                QString album = sqlQuery.value(2).toString();
                int duration = sqlQuery.value(3).toInt();
                int id=sqlQuery.value(4).toInt();
                qDebug()<<QString("songname:%1    singer:%2    album:%3   duration:%4    id:%5").arg(songname).arg(songname).arg(album).arg(duration).arg(id);

                strcpy(s.singer,singer.toStdString().c_str());
                strcpy(s.songname,songname.toStdString().c_str());
                strcpy(s.album_name,album.toStdString().c_str());
                s.music_id=id;
                s.duration2=duration;

                memcpy(msg.buf,&s,sizeof(s));
                clientSocket->write((char*)&msg,sizeof(msg));

                qDebug()<<"发送了"<<i<<"次信号"<<endl;
                i++;


            }

        }
        if(msg.type == 5)//取消喜欢
        {
            song*rn=new song;
            rn = (song *)msg.buf;
            //"DELETE FROM zhanghao WHERE name = '%s' and passwd = '%d';", s1.name, s1.passwd)
            QString str= QString("DELETE FROM like%1 WHERE id=%2;").arg(name).arg(rn->music_id);
            sqliteOP->normalExec(str);
        }
    }

}
void MainWindow::onDisconnected()
{
    if(clientSocket)
    {
        qDebug()<<"客户端未连接"<<endl;
    }
}
